#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#include <sys/wait.h>
#include <cstring>
using namespace std;

#define PATH_NAME "test.cpp"
#define SHM_SIZE 1024

int main()
{
    pid_t pid = fork();
    if (pid > 0)
    {
        // 父进程
        // 创建共享内存
        key_t key = ftok(PATH_NAME, 1);
        int shmid = shmget(key, SHM_SIZE, IPC_CREAT | 0666);
        if (shmid < 0)
        {
            perror("shmget fail");
            exit(1);
        }

        // 连接共享内存
        char* shm = (char*)shmat(shmid, NULL, 0);
        if (shm == (char*)-1)
        {
            perror("shmat fail");
            exit(1);
        }

        // 写入内容
        const char* message = "i am process A";
        strcpy(shm, message);

        // 等待子进程读取
        sleep(1);

        // 分离共享内存
        int n = shmdt(shm);
        if (n < 0)
        {
            perror("shmdt fail");
            exit(1);
        }

        // 删除共享内存
        n = shmctl(shmid, IPC_RMID, NULL);
        if (n < 0)
        {
            perror("shmctl fail");
            exit(1);
        }

        wait(NULL);
    }
    else if (pid == 0)
    {
        // 子进程
        key_t key = ftok(PATH_NAME, 1);
        int shmid = shmget(key, SHM_SIZE, 0666);
        if (shmid < 0)
        {
            perror("shmget fail");
            exit(1);
        }

        // 连接共享内存
        char* shm = (char*)shmat(shmid, NULL, 0);
        if (shm == (char*)-1)
        {
            perror("shmat fail");
            exit(1);
        }

        // 读出内容
        cout << shm << endl;

        // 分离共享内存
        int n = shmdt(shm);
        if (n < 0)
        {
            perror("shmdt fail");
            exit(1);
        }
    }
    else
    {
        perror("fork fail");
        exit(1);
    }

    return 0;
}